<?php
/*
    Authors and license
*/

include_once(dirname(__FILE__).'/../libraries/security.php');

if(!$_SESSION['logged']) { // login status check
    if(isset($_POST['name'])) { // filled name
	
        // Data filter
        $_POST['name'] = clear($_POST['name']);
        $_POST['password'] = $_POST['password'];
        $_POST['password2'] = $_POST['password2'];
        $_POST['email'] = clear($_POST['email']);
 
        // Checking if all areas are filled
        if(empty($_POST['name']) || empty($_POST['password']) || empty($_POST['password2']) || empty($_POST['email'])){
            echo $lang_unfilled_areas;
        }
		
		// Checking if passwords are the same
		elseif($_POST['password'] != $_POST['password2']) { 
            echo $lang_diff_pass;        
        } 
		
		// Email validation
		elseif(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
            echo $lang_email_error;
        } 
		
		else {
            // Checking if user or mail already exists
            $result = mysql_query("SELECT Count(Id) FROM `Users` WHERE `Login` = '{$_POST['name']}' OR `Email` = '{$_POST['email']}'"); // Getting from base amount of users with that Login or E-mail
			
            $row = mysql_fetch_row($result); 
            if($row[0] > 0) { // Are there any?
                echo $lang_user_already_exist;
            } 
			
			//There are no such users in base - new user can be created
			else {
				$ver_code = uniqid(rand()); // random verification code
				
                $_POST['password'] = codepass($_POST['password']); // hashing password function from security.php
				
				mysql_query("INSERT INTO `Users` (`Login`, `Password`, `Email`, `Verification_code`, `Confirmed`, `Reg_date`) VALUES ('{$_POST['name']}', '{$_POST['password']}', '{$_POST['email']}', '{$ver_code}', '0', '".time()."')"); // adding created user to database
				
				mail($_POST['email'], $lang_user_register, $lang_hello.$_POST['name'].$lang_list.$ver_code, "From: <$webmail>"); // sending e-mail with verification code
				
                echo $lang_successfull_reg;
            }
        }
    }
	// user is not registered and user did not fill form
	printRegisterForm($lang_login, $lang_password, $lang_repeat_password, $lang_email, $lang_register);
} 
// user is yet registered
else {
    echo $lang_already_logged;
}

?>
